﻿using System;
using System.ComponentModel;
using System.Windows.Data;

namespace OpenLightGroup.Common.Converters
{
    /// <summary>
    /// Inverts a Boolean value
    /// </summary>
    [Description("Inverts a Boolean value.")]
    public class InverseBooleanConverter
        : IValueConverter
    {

        #region IValueConverter Members

        /// <summary>
        /// Inverts the bound Boolean value.
        /// </summary>
        /// <param name="value">Boolean value to convert.</param>
        /// <param name="targetType">Not used.</param>
        /// <param name="parameter">Default Boolean value</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            bool? output = InvertValue(value);

            if (output == null)
                output = InvertValue(parameter);

            return output;

        }

        /// <summary>
        /// Inverts the bound Boolean value.
        /// </summary>
        /// <param name="value">Boolean value to convert.</param>
        /// <param name="targetType">Not used.</param>
        /// <param name="parameter">Default Boolean value</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool? output = InvertValue(value);

            if (output == null)
                output = InvertValue(parameter);

            return output;
        }

        #endregion

        private static bool? InvertValue(object value)
        {
            bool output;

            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {

                if (bool.TryParse(value.ToString(), out output))
                {
                    return !output;
                }
                else
                {
                    return null;

                }

            }
            else
            {
                return null;
            }

        }
    }
}
